package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

//HTTPGet get 请求
func HTTPGet(uri string) ([]byte, error) {
	response, err := http.Get(uri)
	if err != nil {
		return nil, err
	}

	defer response.Body.Close()
	if response.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("http get error : uri=%v , statusCode=%v", uri, response.StatusCode)
	}
	return ioutil.ReadAll(response.Body)
}

// http server

func sayHello(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	// 1. 请求类型是application/x-www-form-urlencoded时解析form数据
	r.ParseForm()
	fmt.Println(r.PostForm) // 打印form数据
	fmt.Println(r.PostForm.Get("name"), r.PostForm.Get("age"))
	// 2. 请求类型是application/json时从r.Body读取数据
	b, err := ioutil.ReadAll(r.Body)
	if err != nil {
		fmt.Println("read request.Body failed, err:%v\n", err)
		return
	}
	fmt.Println(string(b))


	w.Write([]byte("ok"))
}

func main() {

	go func() {
		fmt.Println("--------------")
		http.HandleFunc("/", sayHello)
		err := http.ListenAndServe(":9090", nil)
		if err != nil {
			fmt.Printf("http server failed, err:%v\n", err)
			return
		}
	}()

	go func() {
		fmt.Println("--------------")
		//http.HandleFunc("/", sayHello)
		http.Handle("/xx", http.FileServer(http.Dir("./html/")))
		http.HandleFunc("/test", sayHello)
		err := http.ListenAndServe(":443", nil)
		if err != nil {
			fmt.Printf("http server failed, err:%v\n", err)
			return
		}
	}()


	chSig := make(chan os.Signal)
	signal.Notify(chSig, syscall.SIGINT, syscall.SIGTERM)
	fmt.Printf("Signal:%+v", <-chSig)
	fmt.Printf("signal, server end...")

}
